#include "../tool/headFile.h"
#include "../tool/sock.h"
#include "../tool/struct.h"
#pragma pack(1)
typedef struct Mark{
	int id;
	char mark_name[50];
	int rows;
}Mark;
typedef struct Goods{
	int id;
	char goods_name[50];
	int price;
	char mark_name[50];
	int rows;
}Goods;
typedef struct shopping{
	char goods_name[50];
	int price;
	char mark_name[50];
	int id;
	char phone[50];
}shopping;
#pragma pack()
//变量
sqlite3* db;
char sql[100];
char phoneNum[50];
char readStr[100];
char writeStr[2048];
int size;
int marktype[]={INT,50};
int goodstype[]={INT,50,INT,50};
int shoptype[]={50,INT,50,INT,50};

void getAllMark(int sockfd,char* rdStr){
	strcpy(sql,"select * from mark;");
	size=sizeof(Mark);
	Mark* markArr=(Mark*)getObjs(db,sql,size,marktype);
	memcpy(writeStr,markArr,2048);
	write(sockfd,writeStr,2048);
}

void getGoods(int sockfd,char* rdStr){
	char** rdStr1=split(rdStr,",");
	sprintf(sql,"select * from goods where mark_name='%s';",rdStr1[1]);
	size=sizeof(Goods);
	Goods* goodsArr=(Goods*)getObjs(db,sql,size,goodstype);
	memcpy(writeStr,goodsArr,2048);
	write(sockfd,writeStr,2048);
}

void getShop(int sockfd,char* rdStr){
	char** rdStr1=split(rdStr,",");
	sprintf(sql,"intsert into shopping values('%s',%d,'%s',null,'%s');",rdStr1[1],rdStr1[2],rdStr1[3],rdStr1[4]);
	size=sizeof(shopping);
	shopping* goodsArr=(shopping*)getObjs(db,sql,size,shoptype);
	memcpy(writeStr,goodsArr,2048);
	write(sockfd,writeStr,2048);
}

void* panduan(void* args){
	int sockfd=*((int *)args);
	sqlite3_open("mark.db",&db);

	strcpy(readStr,"");
	read(sockfd,readStr,100);
	printf("%s\n",readStr);
	if(strstr(readStr,"getAllMark")!=NULL){
		getAllMark(sockfd,readStr);
	}else if(strstr(readStr,"getGoods")!=NULL){
		getGoods(sockfd,readStr);
	}else if(strstr(readStr,"getShop")!=NULL){
		getShop(sockfd,readStr);
	}

	sqlite3_close(db);
	close(sockfd);
}

int main(){
	int listenfd=createServer(7001);
	struct sockaddr_in sockmy;
	int mylen;
	while(1){
		int sockfd=accept(listenfd,(struct sockaddr*)&sockmy,&mylen);
		while(sockfd==-1){
			perror("sockfd");
			close(listenfd);
			exit(EXIT_FAILURE);
		}
		printf("accept....\n");
		panduan(&sockfd);
		//pthread_t t1;
		//pthread_create(&t1,NULL,panduan,&sockfd);
		//pthread_detach(t1);
	}
	close(listenfd);
	return 0;
}
